package io.github.yotta.dict.dao.mybatisplus.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.github.yotta.dict.api.param.SysDictQueryParam;
import io.github.yotta.dict.dao.entity.SysDict;
import io.github.yotta.dict.dao.mybatisplus.mapper.SysDictMybatisPlusMapper;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Objects;

public class SysDictMybatisServiceImpl extends ServiceImpl<SysDictMybatisPlusMapper, SysDict> implements SysDictMybatisService {

    public List<SysDict> list(SysDictQueryParam queryParam) {
        LambdaQueryWrapper<SysDict> queryWrapper = buildQuery(queryParam);
        return this.list(queryWrapper);
    }

    @Override
    public IPage<SysDict> page(SysDictQueryParam queryParam) {
        LambdaQueryWrapper<SysDict> queryWrapper = buildQuery(queryParam);
        return this.page(new Page<>(queryParam.getPageNo(), queryParam.getPageSize()), queryWrapper);
    }

    private LambdaQueryWrapper<SysDict> buildQuery(SysDictQueryParam queryParam) {
        LambdaQueryWrapper<SysDict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(StringUtils.isNotEmpty(queryParam.getId()), SysDict::getId, queryParam.getId())
                .eq(StringUtils.isNotEmpty(queryParam.getTenantId()), SysDict::getTenantId, queryParam.getTenantId())
                .eq(StringUtils.isNotEmpty(queryParam.getCode()), SysDict::getCode, queryParam.getCode())
                .eq(Objects.nonNull(queryParam.getStatus()), SysDict::getStatus, queryParam.getStatus())
                .orderByAsc(SysDict::getSort)
                .orderByDesc(SysDict::getId);
        return queryWrapper;
    }

}